package com.smarth.zhizulian.utils.listhelper.impl.model;

import android.content.Context;

import com.smarth.zhizulian.bean.Page;
import com.smarth.zhizulian.http.observer.inter.IRefreshObserver;
import com.smarth.zhizulian.utils.listhelper.inter.IDataModel;
import com.smarth.zhizulian.utils.listhelper.inter.ResponseSender;

import java.util.List;

import io.reactivex.Observable;

/**
 * Created by 18865 on 2018/1/16.
 */

public abstract class HttpListDataModel<T extends List> implements IDataModel<T> {
    public int mPage = 1;
    public int mMaxPage = 1;
    private Context mContext;

    public HttpListDataModel(Context context) {
        mContext = context;
    }

    @Override
    public void refresh(ResponseSender<T> responseSender) {
        fetch(responseSender, 1);
    }

    @Override
    public void loadMore(ResponseSender<T> responseSender) {
        fetch(responseSender, mPage + 1);
    }

    @Override
    public boolean hasMore() {
        return (mPage + 1) <= mMaxPage;
    }

    public void fetch(final ResponseSender<T> responseSender, int page) {
        getObservable(responseSender, page).subscribe(new IRefreshObserver<Page>(mContext, responseSender) {
            @Override
            public void onNext(Page tPage) {
                super.onNext(tPage);
                List list = tPage.getList();
                mResponseSender.sendData(list);
                mPage = tPage.getPageNo();
                mMaxPage = tPage.getPageNum();
            }
        });
    }

    public abstract Observable<? extends Page> getObservable(ResponseSender<T> responseSender, int page);
}

